package com.esm.pdawms.activity;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.esm.pdawms.R;
import com.esm.pdawms.database.manager.SystemCenter;
import com.esm.pdawms.util.CrashHandler;
import com.esm.pdawms.util.HttpRequest;
import com.esm.pdawms.version.UpdateManager;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.JSON;


public class WelcomeActivity extends BaseActivity implements View.OnClickListener, MyReceiver.Message {

    private ProgressBar progress;


    private TextView tv_msg;
    private EditText edit_yuangong;
    MyReceiver myReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.welcome);

        progress = (ProgressBar) this.findViewById(R.id.progress);

        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);

        tv_msg = (TextView) findViewById(R.id.tv_msg);
        edit_yuangong = (EditText) findViewById(R.id.edit_yuangong);

        //apk版本升级
//        UpdateManager.getUpdateManager().checkAppUpdate(this, false);

        permissonHandle();

        myReceiver = new MyReceiver();
        myReceiver.message = this;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.ACTION_DECODE_DATA");
        intentFilter.addAction("com.scanner.broadcast");
        registerReceiver(myReceiver, intentFilter);

        scancode("xumei"); //默认徐梅登录
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    private void onChukudan() {
        Intent intent = new Intent(this, ChukudanActivity.class);
        startActivity(intent);
    }

    private void onPanku() {
        Intent intent = new Intent(this, PankuActivity.class);
        startActivity(intent);
    }

    private void onHpbh() {
        Intent intent = new Intent(this, HpbhActivity.class);
        startActivity(intent);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    progress.setVisibility(View.GONE);
//                    startApp();
                    break;
            }
        }
    };

    private void start() {
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);

            }
        }.start();
    }

    //    , Manifest.permission.ACCESS_COARSE_LOCATION
    private void permissonHandle() {
        //安卓6.0权限请求
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE}, 111);
        } else {
            AppContext.getInstances().setDatabase();    //初始化数据库
            start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean writeAccepted = false;
        switch (requestCode) {
            case 111:
                writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (writeAccepted) {
                    AppContext.getInstances().setDatabase();    //初始化数据库
                    start();
                } else {
                    moveTaskToBack(false);//应用退到后台
                    System.exit(0);
                }
                break;
        }
    }

    @Override
    public void getMsg(String str) {
        if (!isActive) {
            return;
        }
        scancode(str);
    }

    void scancode(final String esmcode) {
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.esmscan(esmcode, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    dismissProgressDialog();

                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    } else {
                        showShortToast(getString(R.string.wlwlj));
                        return;
                    }

                    if (code == 1) {
                        String data = jsonObject.getString("data");
                        JSONObject jsonObject2 = JSON.parseObject(data);
                        int mode = jsonObject2.getInteger("mode");
                        if (mode == 0) {
                            String name = jsonObject2.getString("name");
                            SystemCenter.getInstance().caozuo = name;
                            edit_yuangong.setText(name);
                            tv_msg.setText("操作请扫码");
                        } else {
                            if (SystemCenter.getInstance().caozuo.isEmpty()) {
                                showShortToast("请先扫员工码登录！");
                            } else {
                                SystemCenter.getInstance().esmcode = esmcode;
                                doNext(mode);
                            }
                        }
                     } else {
                        String msg = jsonObject.getString("msg");
                        showShortToast(msg);
                    }

                }
            });
        } catch (Exception e1) {
            showShortToast(getString(R.string.wlwlj));
            dismissProgressDialog();
        }
    }

    private void doNext(int mode) {
        switch (mode) {
            default:
            case 0:
                break;
            case 1:
                //库位
                onPanku();
                break;
            case 3:
                //扫小标
                onHpbh();
                break;
            case 6:
                //出入库单
                onChukudan();
                break;
        }
    }

    boolean isActive = false;
    @Override
    protected void onPause() {
        super.onPause();
        isActive = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isActive = true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                //返回按键
                finish();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }


}